package com.visionblue.business.ship.page.collection

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.WhichButton
import com.afollestad.materialdialogs.actions.getActionButton
import com.sun.jna.Pointer
import com.visionblue.business.ship.R
import com.visionblue.business.ship.base.BaseVMActivity
import com.visionblue.business.ship.base.DefaultObserver
import com.visionblue.business.ship.model.bean.response.ApplicationDetail
import com.visionblue.business.ship.model.enums.RecordMode
import com.visionblue.business.ship.page.collection.panel.PanelFragment
import com.visionblue.business.ship.page.collection.record.CheckRecordFragment
import com.visionblue.business.ship.page.collection.record.RecordFragment
import com.visionblue.business.ship.page.dialog.TaskSlideDialog
import com.visionblue.business.ship.util.ActivityUtils
import com.visionblue.business.ship.view.popup.ShipDetailInfoPopup
import kotlinx.android.synthetic.main.activity_collection.*
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.getViewModel

/**
 * @author: xlh
 * @date: 2020-05-19 2:21 PM
 * @desc:
 */
open class CollectionActivity : BaseVMActivity<CollectionViewModel>() {
    public var applicationDetail: ApplicationDetail? = null
    private var h = Pointer.NULL
    private val mSlideDialog: TaskSlideDialog by lazy {
        TaskSlideDialog(this)
    }

    override fun initVM(): CollectionViewModel = getViewModel()

    override val layoutId: Int
        get() = R.layout.activity_collection

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        val from = intent.getStringExtra("from")
        if (from == "主页按钮"){
            mViewModel.getApplications()
        }

        //PrinterUtil.printText(this,"12345677654321")


        ActivityUtils.addFragmentToActivity(
            supportFragmentManager,
            PanelFragment.newInstance(),
            R.id.flPanel, PANEL_TAG
        )

        ActivityUtils.addFragmentToActivity(
            supportFragmentManager,
            RecordFragment.newInstance(),
            R.id.flRecord, RECORD_TAG
        )

        tvMainShipName.setOnClickListener {
            showDetailShipInfo()
        }

        tvInfoTitle.text = "接收对象"
        tvInfoTitle.setOnClickListener {
            showDetailShipInfo()
        }

        ivMainClose.setOnClickListener {
            doBack {
                finish()
            }
        }

        btnSelectReceived.setOnClickListener {
            mViewModel.getApplications()
        }

        showNoSelectionView()

    }








//    private fun showFirstWeightGuide() {
//        val rbWeigh =
//            supportFragmentManager.findFragmentByTag(PANEL_TAG)?.view?.findViewById<RadioButton>(R.id.rbWeigh)
//        val ivOp =
//            supportFragmentManager.findFragmentByTag(RECORD_TAG)?.view?.findViewById<ImageView>(R.id.ivOp)
//
//        NewbieGuide.with(this)
//            .setLabel("first_guide")
//            .setShowCounts(1)
//            .addGuidePage(
//                GuidePage.newInstance().addHighLight(rbWeigh)
//                    .setLayoutRes(R.layout.view_guide_weight)
//            )
//            .addGuidePage(
//                GuidePage.newInstance().addHighLight(ivOp)
//                    .setLayoutRes(R.layout.view_guide_work)
//            )
//            .setOnGuideChangedListener(object : OnGuideChangedListener {
//                override fun onShowed(controller: Controller?) {
//
//                }
//
//                override fun onRemoved(controller: Controller?) {
//                    MLog.e("onRemoved...")
//                }
//            })
//            .show()
//    }


    override fun initData() {
        super.initData()

//        flPanel.post {
//            showFirstWeightGuide()
//        }

        val cachedOrderId = intent.getLongExtra(CACHED_ORDER_ID, -1)
        if (cachedOrderId != -1L) {
            launch {
                mViewModel.queryCachedOrderById(cachedOrderId).join()
                mViewModel.getApplicationDetail()?.let { showSelectedView(it) }
            }
        }

        applicationDetail =
                intent.getBundleExtra(DETAIL_KEY)?.getParcelable<ApplicationDetail>(DETAIL_KEY)

        applicationDetail?.let { showSelectedView(it) }

        mViewModel.applicationsState.observe(
                this, DefaultObserver(finallyAction = {
            btnSelectReceived.isEnabled = true
        }, errorAction = {
            mSlideDialog.showError()
        }, loadingAction = {
            btnSelectReceived.isEnabled = false
                mSlideDialog.showLoading()
            }, action = {
                val data = it.data
                if (data != null) {
                    onApplicationsGot(
                        it.data.hasNext(),
                        it.data.hasPre(), data.content

                    )


                }
            })
        )

    }

    fun changeRecordMode(mode: RecordMode) {
        val frag = if (mode == RecordMode.TEXT_MODE) {
            RecordFragment.newInstance()
        } else {
            CheckRecordFragment.newInstance()
        }

        ActivityUtils.addFragmentToActivity(
            supportFragmentManager,
            frag,
            R.id.flRecord
        )
    }

    override fun onBackPressed() {
        doBack {
            super.onBackPressed()
        }
    }

    private fun doBack(action: () -> Unit) {
        if (mViewModel.isIdle()) {
            MaterialDialog(this).show {
                message(res = R.string.not_work_tips_when_clicked_back) {
                    messageTextView.textSize = 22f
                }
                getActionButton(WhichButton.POSITIVE).textSize = 20f
                getActionButton(WhichButton.NEGATIVE).textSize = 20f
                positiveButton(res = R.string.sure_to_quit) {
                    launch {
                        mViewModel.stopWatchWeightInfo()
                        mViewModel.updateCachedOrderByEndTime(System.currentTimeMillis()).join()
                        it.dismiss()
                        action.invoke()
                    }
                }
                negativeButton(res = R.string.cancel) {
                    it.dismiss()
                }
            }
        } else {
            MaterialDialog(this).show {
                message(res = R.string.working_tips_when_clicked_back) {
                    messageTextView.textSize = 22f
                }
                getActionButton(WhichButton.POSITIVE).textSize = 20f
                positiveButton(res = R.string.i_know_that) {
                    it.dismiss()
                }
            }
        }
//        mViewModel.checkCurrWorkStatus(beforeWork = {
//

//        }, working = {

    }

    private fun onApplicationsGot(
        hasNext: Boolean,
        hasPre: Boolean,
        applications: List<ApplicationDetail>
    ) {
        if (applications.isNotEmpty()) {

            mSlideDialog.showContent(
                applications[0],
                hasNext,
                hasPre,
                object : TaskSlideDialog.OnViewsClickListener {
                    override fun onStartCollectClick(detail: ApplicationDetail) {
                        applicationDetail = detail
                        showSelectedView(detail)
                    }

                    override fun onDeclineClick(id: String?) {}
                    override fun onSureReceiveClick(id: String?, detail: ApplicationDetail) {
                        applicationDetail = detail
                    }

                    override fun onPreClick() {
                        mViewModel.prePage()
                    }

                    override fun onNextClick() {
                        mViewModel.nextPage()
                    }

                    override fun onDismiss() {
                        // 每次从第一页开始显示
                        mViewModel.resetPageNum()
                    }

                    override fun onClose() {
                        finish()
                    }
                })
        } else {
            mSlideDialog.showEmpty()
        }
    }

    open fun isOutput(): Boolean = false

    private fun showSelectedView(detail: ApplicationDetail) {
        tvMainShipName.visibility = View.VISIBLE
        tvInfoTitle.visibility = View.VISIBLE
        btnSelectReceived.visibility = View.GONE

        tvMainShipName.text = detail.shipInfo?.shipName ?: "-"
        tvMainShipName.tag = detail

        launch {
            mViewModel.updateCachedOrder(detail.id, detail.shipInfo?.shipName)
                .join()
            mViewModel.cacheApplicationDetail(detail)
        }
    }

    private fun showNoSelectionView() {
        tvMainShipName.visibility = View.GONE
        tvInfoTitle.visibility = View.GONE
        btnSelectReceived.visibility = View.VISIBLE
    }

    private fun showDetailShipInfo() {
        val detail: ApplicationDetail? = tvMainShipName.tag as ApplicationDetail?
        if (detail != null) {
            ShipDetailInfoPopup(this, detail)
                .setBackgroundColor(0)
                .showPopupWindow(view_divider)
        }
    }



    companion object {

        const val CACHED_ORDER_ID = "cachedOrderId"
        private const val DETAIL_KEY = "applicationDetail"
        private const val PANEL_TAG = "panelTag"
        private const val RECORD_TAG = "recordTag"

        fun start(context: Context, from: String, applicationDetail: ApplicationDetail? = null, id: Long? = -1L) {
            Intent(context, CollectionActivity::class.java)
                    .putExtra(DETAIL_KEY, Bundle().apply {
                        putParcelable(DETAIL_KEY, applicationDetail)
                    })
                    .putExtra(CACHED_ORDER_ID, id)
                    .putExtra("from", from)
                    .run {
                        context.startActivity(this)
                    }
        }
    }
}